package com.oscarmovie;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import tt.util.HtmlUtils;
import tt.util.IOUtils;

public class DoubanMovie {
	public static void main(String[] args) throws Exception {
		// searchDoubanId("American in Paris","subject");
		// searchMovieDoubanIds();
		// searchAllMovies();

		// List<String> images = searchSingleMovieImages(1401388);System.out.println(images);

	}

	// ///////////////////////////////////////////////////////////////////////////////
	// Search movie images from douban ///////////////////////////////////////////
	// /////////////////////////////////////////////////////////////////////////////
	public static void searchAllMovieImages() {
		List<HashMap<Object, Object>> select = Tools.retrieveObjectWithDoubanIds("movie");
		int size = select.size();
		int i = 0;
		for (HashMap<Object, Object> hm : select) {
			int id = ((BigDecimal) hm.get("ID")).intValue();
			int doubanId = ((BigDecimal) hm.get("DOUBAN_ID")).intValue();
			doubanId = Math.abs(doubanId);
			System.out.println("============================================================");
			System.out.println("No. " + (++i) + "/" + size + ": " + id + ", " + doubanId);
			List<String> images = searchSingleMovieImages(doubanId);
			System.out.println("images.size: " + images.size());
			for (String image : images) {
				int imageId = Tools.createImage(image);
				Tools.createRelationShip("movie_image", id, imageId);
			}
			Tools.updateDoubanIdFlag(id);
		}
	}

	private static List<String> searchSingleMovieImages(int mtimeId) {
		List<String> list = new ArrayList<String>();
		String url = movieImages(mtimeId);
		System.out.println("URL: " + url);
		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "UTF-8");
		for (String s : readFileAsList) {
			s = s.trim();
			// if(!s.equals(""))System.out.println(s);
			if (s.indexOf("albumicon") != -1) {
				String pageurl = HtmlUtils.parse(s, "<a href=\"", "\"");
				list.add(searchSingleMovieImage(pageurl));
			}
		}
		System.out.println();
		return list;
	}

	private static String searchSingleMovieImage(String url) {
		String imgurl = null;
		// System.out.println("URL: " + url);
		System.out.print(".");
		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "UTF-8");
		int i = 0;
		for (String s : readFileAsList) {
			s = s.trim();
			// if(!s.equals(""))System.out.println(s);
			if (i == 1) {
				imgurl = HtmlUtils.parse(s, "src=\"", "\"");
				break;
			}
			if (s.indexOf("mainphoto") != -1) {
				i++;
			}

		}
		return imgurl;
	}

	
	private static String movieImages(int doubanId) {
		return "http://movie.douban.com/subject/" + doubanId + "/all_photos";
	}
/////////////////////////////////////////////////////////////////////////////
	// Search movie information from douban ///////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
	public static void searchAllMovies() {
		List<HashMap<Object, Object>> select = Tools.retrieveObjectWithDoubanIds("movie");
		int size = select.size();
		int i = 0;
		for (HashMap<Object, Object> hm : select) {
			int movieId = ((BigDecimal) hm.get("ID")).intValue();
			int doubanId = ((BigDecimal) hm.get("DOUBAN_ID")).intValue();
			System.out.println("============================================================");
			System.out.println("No. " + (++i) + "/" + size + ": " + movieId + ", " + doubanId);
			try {
				// get movie detailed info
				HashMap<String, String> movieInfo = searchSingleDoubanMovie(doubanId);
				String ss = movieInfo.get("languages");
				String languages[] = ss == null ? null : ss.split("/");

				ss = movieInfo.get("categories");
				String categories[] = ss == null ? null : ss.split("/");

				ss = movieInfo.get("countries");
				String countries[] = ss == null ? null : ss.split("/");

				Tools.updateMovie(movieId, movieInfo.get("v:itemreviewed"), movieInfo.get("v:runtime"),
						movieInfo.get("v:initialReleaseDate"), movieInfo.get("v:summary"), movieInfo.get("v:image"),
						languages, categories, countries);
			} catch (Exception e) {
				System.err.println("Caught runtime exception");
				e.printStackTrace();
			}
			// if(i==1)return;
		}
	}

	private static HashMap<String, String> searchSingleDoubanMovie(int doubanId) {
		HashMap<String, String> hm = new HashMap<String, String>();
		String url = douban(doubanId, "subject");
		System.out.println("Douban URL: " + url);
		int i = 0;
		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "UTF-8");
		for (String s : readFileAsList) {
			s = s.trim();
			// System.out.println((++i)+": "+s);
			if (s.indexOf("v:itemreviewed") != -1) {
				// System.out.println(s);
				String pattern = "v:itemreviewed";
				int p1 = s.indexOf(pattern);
				p1 += pattern.length() + 2;
				int p2 = s.indexOf("</span>", p1);
				String ss = s.substring(p1, p2);
				// System.out.println(ss);
				hm.put("v:itemreviewed", "" + ss);

			} else if (s.indexOf("v:image") != -1) {
				// System.out.println(s);
				String pattern = "src=\"";
				int p1 = s.indexOf(pattern);
				p1 += pattern.length();
				int p2 = s.indexOf("\" title", p1);
				String ss = s.substring(p1, p2);
				// System.out.println(ss);
				hm.put("v:image", "" + ss);

			} else if (s.indexOf("v:runtime") != -1) {
				// System.out.println(s);
				String ss = parse(s);
				// System.out.println(ss);
				hm.put("v:runtime", "" + ss);

			} else if (s.indexOf("v:initialReleaseDate") != -1) {
				// System.out.println(s);
				String ss = parse(s);
				// System.out.println(ss);
				hm.put("v:initialReleaseDate", "" + ss);

			} else if (s.indexOf("v:summary") != -1) {
				// System.out.println(s);
				String pattern = "summary";
				int p1 = s.indexOf(pattern);
				p1 += pattern.length() + 2;
				int p2 = s.indexOf("</span>", p1);
				String ss = null;
				if (p2 != -1)
					ss = s.substring(p1, p2);
				else
					ss = s.substring(p1);
				hm.put("v:summary", "" + ss);
			} else if (s.indexOf("v:genre") != -1) {
				// System.out.println(s);

				String ss = parse2(s);

				// System.out.println(ss);
				ss = ss.replace("</span>", "<-span>");
				String sss[] = ss.split("/");
				String newStr = "";
				for (String ssss : sss) {

					// System.out.println(ssss);
					String sssss = parse3(ssss);
					newStr += newStr.equals("") ? sssss : "/" + sssss;

				}
				// System.out.println(newStr);
				hm.put("categories", "" + newStr);
			} else if (s.indexOf("制片国家/地区") != -1) {
				// System.out.println(s);
				String ss = parse2(s);

				// System.out.println(ss);
				hm.put("countries", "" + ss);

			} else if (s.indexOf("语言:") != -1) {
				// System.out.println(s);
				String ss = parse2(s);

				// System.out.println(ss);
				hm.put("languages", "" + ss);

			} else if (s.indexOf("又名") != -1) {
				// System.out.println(s);
				String ss = parse2(s);

				// System.out.println(ss);
				hm.put("names", "" + ss);

			}

		}

		return hm;
	}

	private static String parse(String s) {
		String pattern = "content";
		int p1 = s.indexOf(pattern);
		p1 += pattern.length() + 2;
		int p2 = s.indexOf("\"", p1);
		String content = s.substring(p1, p2);
		return content;
	}

	private static String parse2(String s) {
		String ss = s;
		try {

			String pattern = "</span>";
			int p1 = s.indexOf(pattern);
			p1 += pattern.length();
			int p2 = s.indexOf("<br/>", p1);
			ss = s.substring(p1, p2);

		} catch (Exception e) {
			System.out.println(s);
		}
		return ss;
	}

	private static String parse3(String s) {
		String pattern = "v:genre";
		int p1 = s.indexOf(pattern);
		p1 += pattern.length() + 2;
		int p2 = s.indexOf("<-span>", p1);
		String ss = s.substring(p1, p2);
		return ss;
	}
/////////////////////////////////////////////////////////////////////////////
	// Search douban id from baidu ///////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
	public static void searchMovieDoubanIds() {
		List<HashMap<Object, Object>> select = Tools.retrieveObjectWithoutDoubanId("movie");
		int size = select.size();
		int i = 0;
		for (HashMap<Object, Object> hm : select) {
			int movieId = ((BigDecimal) hm.get("ID")).intValue();
			String movieName = (String) hm.get("NAME");
			String movieNameCn = (String) hm.get("NAME_CN");
			String n = movieNameCn != null && !movieNameCn.equals("") ? movieNameCn : movieName;
			System.out.println("============================================================");
			System.out.println("No. " + (++i) + "/" + size + ", " + movieId + ", " + n);
			int doubanId = searchDoubanId(n, "subject");
			Tools.updateMovieDoubanId(movieId, doubanId);
		}
	}

	private static String douban(int doubanId, String s) {
		return "http://movie.douban.com/" + s + "/" + doubanId + "/";
	}

	public static int searchDoubanId(String key, String ss) {
		int id = 0;
		String url = baiduDouban(key);
		System.out.println(url);
		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "GBK");
		for (String s : readFileAsList) {
			String pattern = "http://movie.douban.com/" + ss + "/";
			int p1 = s.indexOf(pattern);
			if (p1 != -1) {
				// System.out.println(s);
				p1 += pattern.length();
				int p2 = p1 + 7;
				String i = s.substring(p1, p2);
				try {
					id = Integer.parseInt(i);
				} catch (Exception e) {
					System.out.println("ERR: " + i);
				}
				System.out.println(id);
				break;
			}
		}
		return id;
	}

	private static String baiduDouban(String key) {
		return "http://www.baidu.com/s?wd=豆瓣+" + key.replace(" ", "+") + "&rsv_bp=0&rsv_spt=3&n=2&inputT=12529";
	}
}
